<template>
  <el-container class="official-account-management_mass-message">
    <el-main>
      <el-card shadow="never" class="tableCard">
        <vxe-toolbar :custom="{icon: 'el-icon-s-operation'}" :refresh="{query: getList}" print>
          <template v-slot:buttons>
            <el-button type="primary" icon="el-icon-plus" @click="openDialog({id: ''})">新增</el-button>
            <!-- <el-button type="primary" icon="el-icon-download">导出</el-button> -->
            <!-- <el-button type="warning" icon="el-icon-connection">一键授权添加</el-button> -->
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          border
          resizable
          highlight-hover-row
          :loading="loading"
          :auto-resize="true"
          :data="list"
          width
          max-height="500"
          :print-config="{}"
        >
          <vxe-table-column width="180" field="createTime" align="center" title="创建时间" />
          <vxe-table-column width="120" align="center" title="是否全部用户">
            <template slot-scope="scope">
              {{ scope.row.scope === 1 ? '是' : '否' }}
            </template>
          </vxe-table-column>
          <vxe-table-column width="100" field="messageType" align="center" title="消息类型">
            <template slot-scope="scope">
              <span v-if="scope.row.messageType === '1'">图文</span>
              <span v-if="scope.row.messageType === '2'">图片</span>
              <span v-if="scope.row.messageType === '3'">音频</span>
              <span v-if="scope.row.messageType === '4'">视频</span>
              <span v-if="scope.row.messageType === '5'">文本</span>
            </template>
          </vxe-table-column>
          <vxe-table-column width="400" field="content" title="内容" />
          <vxe-table-column width="120" field="sendStatus" align="center" title="消息发送状态" />
          <vxe-table-column width="100" field="sendCount" align="center" title="发送的总数" />
          <vxe-table-column width="100" field="filterCount" align="center" title="过滤后总数" />
          <vxe-table-column width="100" field="successCount" align="center" title="发送成功数" />
          <vxe-table-column width="100" field="failedCount" align="center" title="发送失败数" />
          <vxe-table-column title="操作" fixed="right" align="center" width="180" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" icon="el-icon-edit" @click="openDialog(scope.row)">查看</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          :current-page.sync="params.pageNum"
          :page-size.sync="params.pageSize"
          :total="total"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          @page-change="getList()"
        />
      </el-card>
    </el-main>
    <el-dialog v-if="dialogFormVisible" :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form ref="ruleForm" :model="dialogParams" :disabled="title === '查看'" :rules="rules" label-width="8rem">
        <el-row :gutter="20" class="mb15">
          <el-col :span="24">
            <el-form-item label="全部用户发送：" prop="allSend">
              <div>
                <el-select v-model="dialogParams.allSend" class="w200">
                  <el-option label="是" value="1" />
                  <el-option label="否" value="2" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogParams.allSend == 2" :span="24">
            <el-form-item label="发送类型：" prop="sendType">
              <div>
                <el-select v-model="dialogParams.sendType" class="w200">
                  <el-option label="指定标签" value="1" />
                  <el-option label="指定用户" value="2" />
                </el-select>
                <span style="padding: 0 5px" />
                <el-select v-if="dialogParams.sendType == 1" v-model="dialogParams.tagIdsF" class="w200" filterable placeholder="请选择">
                  <el-option v-for="item in tagTypeList" :key="item.index" :label="item.name" :value="item.id" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col v-if="dialogParams.allSend == 2 && dialogParams.sendType == 2" :span="24">
            <el-form-item label="指定用户：" prop="chooseType">
              <el-button icon="el-icon-plus" @click="openFansDialog">选择用户</el-button>
              <span v-if="dialogParams.chooseType !== ''">已选中{{ chooseNum }}人</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="回复消息：" class="widthAuto">
              <WxReplySelect ref="WxReplySelect" :obj-data="tempObj" @updateMenu="updateMenu" />
              <!-- <UserMessage ref="userMessage" :key="dialogParams.appId" :isdisabled="title === '查看'" :mp-id="dialogParams.appId" /> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="title !== '查看'" type="primary" @click="clickSure">确 定</el-button>
      </div>
      <el-dialog title="选择用户" :close-on-click-modal="false" :visible.sync="innerVisible" append-to-body>
        <el-form class="search" label-position="right" label-width="6rem">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="是否订阅">
                <el-select v-model="fansParams.subscribe">
                  <el-option :value="''" label="全部" />
                  <el-option :value="1" label="已订阅" />
                  <el-option :value="0" label="未订阅" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别">
                <el-select v-model="fansParams.sex">
                  <el-option :value="''" label="全部" />
                  <el-option :value="1" label="男" />
                  <el-option :value="2" label="女" />
                  <el-option :value="0" label="未选择" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="昵称">
                <el-input v-model="fansParams.nickName" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="关注时间">
                <el-date-picker v-model="fansParams.subscribeStartTime" type="datetime" />
                <i>至</i>
                <el-date-picker v-model="fansParams.subscribeEndTime" type="datetime" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="渠道来源">
                <el-select v-model="fansParams.subscribeScene">
                  <el-option :value="''" label="全部" />
                  <el-option v-for="item in subscribeSceneList" :key="item.index" :value="item.id.toString()" :label="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="取消关注时间">
                <el-date-picker v-model="fansParams.cancelSubscribeStartTime" type="datetime" />
                <i>至</i>
                <el-date-picker v-model="fansParams.cancelSubscribeEndTime" type="datetime" />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="mb15">
              <SearchButton :default-params="params" @refreshParams="refreshFansList" @getList="getFansList" />
            </el-col>
          </el-row>
          <vxe-table
            ref="listTree"
            border
            resizable
            highlight-hover-row
            :loading="loading"
            :auto-resize="true"
            :data="fansList"
            width
            max-height="300"
            :print-config="{}"
            row-id="openId"
            highlight-current-row
            text-algin="center"
            :checkbox-config="{checkRowKeys: checkList, checkStrictly: false}"
            @checkbox-all="selectAll"
            @checkbox-change="selectChangeEvent"
          >
            <vxe-table-column type="checkbox" width="35" />
            <vxe-table-column width="70" title="头像">
              <template slot-scope="scope">
                <img width="50" height="50" :src="scope.row.headImgurl" alt="">
              </template>
            </vxe-table-column>
            <vxe-table-column width="150" field="nickName" title="昵称" />
            <vxe-table-column width="80" title="是否订阅">
              <template slot-scope="scope">
                <span>{{ scope.row.subscribe === 1 ? '已订阅' : '未订阅' }}</span>
              </template>
            </vxe-table-column>
            <vxe-table-column width="250" field="openId" title="openId" />
            <vxe-table-column width="100" field="subscribeSceneName" title="关注渠道" />
            <vxe-table-column width="150" field="subscribeTime" title="关注时间" />
            <vxe-table-column width="50" field="sexName" title="性别" />
            <vxe-table-column width="150" title="地区">
              <template slot-scope="scope">
                {{ scope.row.country }} {{ scope.row.province }} {{ scope.row.city }}
              </template>
            </vxe-table-column>
            <vxe-table-column width="100" field="language" title="语言" />
            <vxe-table-column width="100" field="tags" title="标签" />
            <vxe-table-column width="100" field="remark" title="备注" />
            <vxe-table-column width="100" field="qrScene" title="二维码扫描场景" />
            <vxe-table-column width="150" field="qrSceneStr" title="关注次数" />
          </vxe-table>
          <vxe-pager
            :current-page.sync="fansParams.pageNum"
            :page-size.sync="fansParams.pageSize"
            :total="fansTotal"
            :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
            @page-change="getFansList(fansParams.pageNum)"
          />
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-dropdown style="margin: 0 0 0 10px" placement="bottom-start" @command="chooseFans">
            <el-button type="primary">
              确定<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :disabled="checkList.length === 0" command="1">选择选中的人</el-dropdown-item>
              <el-dropdown-item command="2">选择筛选出来的{{ fansTotal }}人</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-dialog>
    </el-dialog>
  </el-container>
</template>

<script>
import { viewMassMessage, listMassMessagePage, addMassMessage, checkVaildWxMp, listWxMpFans } from '@/api/wxMp'

import { searchAllDictionaries } from '@/api/public'
import SearchButton from '@/components/SearchButton'
import WxReplySelect from '@/components/wechat-mp/reply'
export default {
  components: {
    WxReplySelect,
    SearchButton
  },
  data() {
    return {
      tempObj: {
        sourceType: 'TEXT',
        unionKey: '',
        mpSourceNewsPageVos: [],
        appId: '',
        repUrl: '',
        repName: ''
      },
      subscribeSceneList: [],
      checkList: [],
      fansParams: {
        appId: '',
        subscribe: '',
        openId: '',
        unionId: '',
        nickName: '',
        sex: '',
        subscribeStartTime: '',
        subscribeEndTime: '',
        cancelSubscribeStartTime: '',
        cancelSubscribeEndTime: '',
        subscribeScene: '',
        tagsId: '',
        pageNum: 1,
        pageSize: 20
      },
      fansTotal: 1,
      innerVisible: false,
      rules: {
        'allSend': [{ required: true, message: '请选择用户', trigger: 'change' }],
        'sendType': [{ required: true, message: '请选择发送类型', trigger: 'change' }],
        'chooseType': [{ required: true, message: '请选择指定用户', trigger: 'blur' }]
      },
      tagTypeList: [],
      dialogFormVisible: false,
      params: {
        appId: '',
        allSend: '',
        messageType: '',
        sendCountBegin: '',
        sendCountEnd: '',
        filterCountBegin: '',
        filterCountEnd: '',
        successCountBegin: '',
        successCountEnd: '',
        failedCountBegin: '',
        failedCountEnd: '',
        createTimeBegin: '',
        createTimeEnd: '',
        pageNum: 1,
        pageSize: 20
      },

      list: [],
      fansList: [],
      chooseNum: '',
      title: '',
      loading: false,
      tableCurrentPage: 1,
      pageSize: 20,
      total: 0,
      dialogParams: {
        appId: '',
        allSend: '',
        sendType: '',
        message: {},
        tagIdsF: '',
        tagIds: [],
        userObject: {
          mpFansPageQuery: {},
          userIds: []
        },
        chooseType: ''
      }
    }
  },
  created() {
    this.getAppIdList()
    this.getTagTypeList()
    this.getSubscribeSceneList()
  },
  methods: {
    updateMenu(val) {
      this.dialogParams.message = val
    },
    openFansDialog() {
      this.dialogParams.chooseType = ''
      this.getFansList()
    },
    chooseFans(i) {
      if (i === '1') {
        this.dialogParams.userObject.userIds = this.checkList
        this.chooseNum = this.checkList.length
      } else {
        this.chooseNum = this.fansTotal
        this.dialogParams.userObject.userIds = []
        this.checkList = []
        this.dialogParams.userObject.mpFansPageQuery = JSON.parse(JSON.stringify(this.fansParams))
      }
      this.dialogParams.chooseType = i
      this.innerVisible = false
    },
    getTagTypeList() {

    },
    clickSure() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const type = this.$refs.WxReplySelect.parentParams.sourceType
          const content = this.dialogParams.message.unionKey === undefined ? '' : this.dialogParams.message.unionKey
          const tagNum = this.dialogParams.tagIdsF
          const arr = tagNum === '' ? [] : [tagNum]
          if (this.dialogParams.allSend === '2' && this.dialogParams.sendType === '1' && arr.length === 0) {
            this.$message.error('请选择标签')
            return false
          }
          this.dialogParams.tagIds = arr
          if (type === 'TEXT' && content === '') {
            this.$message.error('请输入文本')
            return false
          } else if (type === 'PIC' && content === '') {
            this.$message.error('请选择图片')
            return false
          } else if (type === 'VOICE' && content === '') {
            this.$message.error('请选择音频')
            return false
          } else if (type === 'VIDEO' && content === '') {
            this.$message.error('请选择视频')
            return false
          } else if (type === 'IMAGE_TEXT' && content === '') {
            this.$message.error('请选择图文')
            return false
          }
          addMassMessage(this.dialogParams).then(res => {
            this.$message.success('新增成功！')
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    refreshParams(params) {
      this.params = params
      this.getList()
    },
    getList1() {
      this.getList()
    },
    openDialog(info) {
      this.chooseNum = ''
      this.dialogParams.chooseType = ''
      this.title = info.id === '' ? '新增' : '查看'
      if (info.id !== '') {
        viewMassMessage({ id: info.id }).then(res => {
          this.dialogParams = res
          this.tempObj = res.message
          this.dialogFormVisible = true
        })
      } else {
        this.dialogParams = {
          allSend: '',
          sendType: '',
          message: {},
          tagIdsF: '',
          tagIds: [],
          userObject: {
            mpFansPageQuery: {},
            userIds: []
          },
          chooseType: ''
        }
        this.tempObj = {
          sourceType: 'TEXT',
          unionKey: '',
          mpSourceNewsPageVos: [],
          repUrl: '',
          repName: ''
        }
        this.tempObj.appId = this.params.appId
        this.dialogParams.appId = this.params.appId
        this.dialogFormVisible = true
      }
    },
    getAppIdList() {
      checkVaildWxMp().then(res => {
        this.setAppId(res.appId)
        this.getList()
      })
    },
    setAppId(appId) {
      this.params.appId = appId
      this.dialogParams.appId = appId
      this.fansParams.appId = appId
      this.tempObj.appId = appId
    },
    getList() {
      listMassMessagePage(this.params).then(res => {
        this.list = res.records
        this.total = res.total
      })
    },
    selectAll(e) {
      if (e.checked) {
        this.checkList.push(...e.records.map(item => item.openId))
        this.checkList = Array.from(new Set(this.checkList))
      } else {
        const arr = this.list.map(item => item.openId)
        const arr1 = []
        this.checkList.forEach((item, index) => {
          arr.forEach(it => {
            if (item === it) {
              arr1.push(index)
            }
          })
        })
        arr1.reverse().forEach(item => {
          this.checkList.splice(item, 1)
        })
      }
    },
    selectChangeEvent(row) {
      let i = -1
      this.checkList.forEach((item, index) => {
        if (item === row.row.openId) {
          i = index
        }
      })
      if (i === -1) {
        this.checkList.push(row.row.openId)
      } else {
        this.checkList.splice(i, 1)
      }
    },
    getSubscribeSceneList() {
      searchAllDictionaries({ type: 'mp_scene_type' }).then(res => {
        this.subscribeSceneList = res
      })
    },
    refreshFansList(params) {
      this.fansParams = params
      this.getFansList()
    },
    getFansList(num = 1) {
      this.fansParams.pageNum = num
      listWxMpFans(this.fansParams).then(res => {
        this.innerVisible = true
        this.$nextTick(() => {
          this.checkList.forEach((item, index) => {
            res.records.forEach((it, idx) => {
              if (item === it.openId) {
                this.$refs.listTree.setCheckboxRow(res.records[idx], true)
              }
            })
          })
          this.fansList = res.records
          this.fansTotal = res.total
        })
      })
    }
  }
}
</script>

<style lang="scss">
.official-account-management_mass-message {}
</style>
